package com.megalith.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.megalith.entities.Person;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author lfp
 * @Date 2021/6/23 14:38
 * @Version 1.0
 */
@RestController
@RequestMapping("okhttp3")
@Slf4j
public class HttpController {

    /**
    *@Description get 请求
    *@param url
    *@Return
    */
    @GetMapping("get")
    public String getRequest(@RequestParam("url") String url) throws IOException {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String res = response.body().string();//response.body()只能调用一次

            log.info("Response ====> :"+res);
            return res;
        }
    }

    /**
     *@Description post 请求
     *@Return
     */
    @PostMapping("post")
    public Person postRequest(@RequestBody Person person) throws IOException {

        //参数封装
        Map param = new HashMap<String,Object>();
        param.put("name",person.getName());
        param.put("nickName",person.getNickName());
        param.put("age",person.getAge());
        //将对象转成json字符串
        String jsonString = JSONObject.toJSONString(param);

        //测试post地址
        String reqUrl = "http://localhost:8099/other/create";

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON, jsonString);
        Request request = new Request.Builder()
                .url(reqUrl)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            String res = response.body().string();//只能调一次

            //拿到响应以后，转换为对象
            Person result = com.alibaba.fastjson.JSON.parseObject(res, Person.class);
            return result;
        }
    }
}
